// const axios = require("./axios/axios.min.js");
import axios from './axios/axios.min'
import config from "./config";

let userConfig = config.getConfig;

let request = axios.create({
  baseURL: userConfig()["default"].baseURL,
  timeout: userConfig()["default"].timeout,
});

request.interceptors.request.use(
  (config) => {
    // 处理用户配置项
    handUserConfig(config);
    // get请求映射params参数
    handParams(config);
    if (userConfig().isUni) {
      config.adapter = uniAdapter;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (response) => {
    const res = response.data;
    return res;
  },
  (error) => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

const handParams = (config) => {
  if (config.method === "get" && config.params) {
    let url = config.url + "?";
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof value !== "undefined") {
        if (typeof value === "object") {
          for (const key of Object.keys(value)) {
            const params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
};
const uniAdapter = (config) => {
  try {
    uni;
  } catch {
    throw new Error("不要在非UNIAPP项目中配置 isUni 为 true");
  }
  return new Promise((resolve, reject) => {
    const { headers, data, params } = config;
    const uniConfig = {
      ...config,
      header: headers,
    };

    if (data || params) {
      try {
        uniConfig.data = JSON.parse(data || params);
      } catch (e) {
        uniConfig.data = data || params;
      }
    }
    uni.request({
      ...uniConfig,
      success(res) {
        resolve({
          ...res,
          headers: res.header,
        });
      },
      fail(res) {
        reject({
          ...res,
          headers: res.header,
        });
      },
    });
  });
};

function handUserConfig(conf) {
  if (conf.url.slice(0, 1) == "/") {
    conf.url = conf.url.slice(1);
  }

  let urlList = conf.url.split("/");
  const apiKey = urlList[0];
  if (Object.keys(userConfig()).some((key) => key === apiKey)) {
    // 去除URL前缀
    urlList[0] = "";
    conf.url = urlList.join("/");

    // 处理header参数
    handHeader(conf, apiKey);
  } else {
    handHeader(conf);
  }
}

function handHeader(conf, apiKey = "default") {
  const currConf = userConfig();

  // 修改基础url
  conf.baseURL = currConf[apiKey].baseURL;
  conf.timeout = currConf[apiKey].timeout;
  if (currConf[apiKey].headers) {
    conf.headers = Object.assign(conf.headers, currConf[apiKey].headers);
  }
}

export default request;
